package maosui.websocket;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.Date;
import java.util.HashMap;

/**
 * Created by wdj on 14-8-7.
 */
public class Utils {

    public static boolean isJSONString(String str){
        return (str.charAt(0) == '{' ||  str.charAt(0) == '[') && (str.endsWith("}") || str.endsWith("]"));
    }

    public static boolean isJSONObject(String str){
        return str.startsWith("{") && str.endsWith("}");
    }

    public static boolean isJSONArray(String str){
        return str.startsWith("[") && str.endsWith("]");
    }

    public static boolean isJSONObject(Object obj){
        return obj instanceof JSONObject;
    }

    public static boolean isJSONArray(Object obj){
        return obj instanceof JSONArray;
    }

    public static String ConvertToEventMessage(String eventType, Object message){

        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("event_type", eventType);
        map.put("event_data", message);
        map.put("event_time", new Date().getTime());
        return JSONObject.fromObject(map).toString();
        //return String.format("{\"event_type\":\"%s\", \"event_data\":%s}",eventType, msg);
    }

    public static HashMap<String, String> parseString(String str){
        if(str == null || str.indexOf("=") == -1 && str.length() == 0)return null;
        String[] s ;
        if(str.indexOf('&') > -1){
            s = str.split("&");
        }else{
            s = new String[]{str};
        }
        HashMap<String,String> map = new HashMap<String, String>();
        for(int i=0;i<s.length;i++){
            if(s[i].indexOf('=') > -1){
                String[] p = s[i].split("=");
                if(p.length == 2 && p[0].length() > 0 && p[1].length() > 0){
                    map.put(p[0],p[1]);
                }
            }
        }
        return map;
    }
}
